<template>
  <div class="login-form">
    <div class="g-form">
      <div class="g-form-line">
        <span class="g-form-label">用户名：</span>
        <div class="g-form-input">
          <input type="text" placeholder="请输入用户名" v-model="user">
        </div>
        <!-- 利用计算属性判断当前用户输入的账号格式是否正确 -->
        <span class="g-form-error"> {{ userError.errorText }} </span>
      </div>
      <div class="g-form-line">
        <span class="g-form-label">密码：</span>
        <div class="g-form-input">
          <input type="password" placeholder="请输入密码" v-model="password">
        </div>
        <span class="g-form-error"> {{ passwordErroe.errorText4 }} </span>
      </div>
      <div class="g-form-line">
        <div class="g-form-btn">
          <a class="button" @click="Login" >登录</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      user: '',
      password: '',
      errorText: ''
    }
  },
  computed: {
    userError() {
      let errorText, status
      if(!/@/g.test(this.user)){
        return {
          status: false,
          errorText: '您输入的账号格式有问题'
        }
      } else {
        return {
          status: true,
          errorText: '',
        } 
      }
      // 变量未声明就是 undefined 但是 为 true
      if (!this.userFlag) {
        errorText = ''
        this.userFlag = true
      }
      
      return { status, errorText}
    },
    passwordErroe() {
      if(!/^\w{1,6}$/g.test(this.password)){
        return {
          status: false,
          errorText: '您输入的密码大于6位'
        }
      } else {
        return {
          status: true,
          errorText: ''
        }
      }
      if (!this.passwordFlag) {
        errorText = ''
        this.passwordFlag = true
      }
      return { status, errorText}
    }
  },
  methods: {
    Login() {
      if(!this.userError.status || !this.passwordErroe.status) {
        this.errorText =  '您的账号或者密码有问题'
      } else {
        // 将表单值post 请求发送给服务端
        this.$http.get('/api/login')
        .then(res => {
          this.$emit('hasLog', res.data)
        }, err => {
          console.log(res.err)  
        })
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
